package com.luyuan.crm.member.web;

import javax.annotation.Resource;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.luyuan.crm.member.model.Address;
import com.luyuan.crm.member.model.Customer;
import com.luyuan.crm.member.model.Region;
import com.luyuan.crm.member.service.CustomerService;
import com.luyuan.crm.member.service.RegionService;
import com.ruijie.web.jsf.action.BaseAction;
import com.ruijie.util.StringUtils;

@Component("customerAction")
@Scope("view")
public class CustomerAction extends BaseAction implements InitializingBean {

    @Resource(name = "customerService")
    private CustomerService customerService;

    @Resource(name = "regionService")
    private RegionService regionService;

    private Customer customer;

    public void add() {
        customerService.addCustomer(customer);

        addGlobalI18nMessage("新建客户信息成功！");
    }

    public void update() {
        customerService.updateCustomer(customer);

        addGlobalI18nMessage("修改客户信息成功！");
    }

    public Customer getCustomer() {
        if (customer == null) {
            customer = new Customer();
            customer.setAddress(new Address());
        }
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    public void resetPostCode(ActionEvent event) {
        String province = null, city = null, region = null;

        UIInput uiInput = (UIInput) FacesContext.getCurrentInstance().getViewRoot().findComponent("userForm:province");
        if (uiInput != null) {
            province = (String) uiInput.getValue();
        }

        uiInput = (UIInput) FacesContext.getCurrentInstance().getViewRoot().findComponent("userForm:city");
        if (uiInput != null) {
            city = (String) uiInput.getValue();
        }

        uiInput = (UIInput) FacesContext.getCurrentInstance().getViewRoot().findComponent("userForm:region");
        if (uiInput != null) {
            region = (String) uiInput.getValue();
        }

        Region r = regionService.getByRegion(province, city, region);
        if (r != null) {
            customer.getAddress().setPostCode(r.getId());
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        String id = getRequestParameter("memberId");
        if (StringUtils.isNotEmpty(id)) {
            customer = customerService.getById(id);
        }

    }
}
